package com.hai.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hai.entity.User;
import com.hai.mapper.UserMapper;
import com.hai.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hai.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Path;
import java.sql.Wrapper;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author NieChangan
 * @since 2022-05-21
 */
@Service
public class UserServiceImp extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public String login(String username, String password) {
        return null;
    }

    @Override
    public User findUserByName(String name) {
        User user = new User();
        user.setUsername(name);
        QueryWrapper<User> wrapper = new QueryWrapper<>(user);
        return  this.baseMapper.selectOne(wrapper);
    }

    @Override
    public Page<User> getUserByPage(Page<User> page, UserVO userVO) {
        List<User> userList = this.baseMapper.getUserList(page, userVO);
        //将刚刚查询的内容给page对象，让其实现分页
        page.setRecords(userList);
        return page;
    }

    @Override
    public void exportUserExcel(HttpServletResponse response, List<User> tbUsers) throws IOException {

        //----- 写入excel文件
        // 设置文件名称
        String exportFileName = "TbUserInfo.xlsx";
        //设置格式 如果没有response 响应 导出数据会出现乱码
        response.setCharacterEncoding("UTF-8");
        //以下载附件的方式进行
        response.setContentType("application/vnd.ms-excel");

        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(tbUsers);
    }

    @Override
    public List<User> getUserListToExcel(UserVO userVO) {
        return this.baseMapper.getUserListToExcel(userVO);
    }
}
